<template>
    <div>
        <!--注册、登录、退出登录按钮-->
        <el-row>
            <el-button plain @click="registerVisible = true" v-if="!isLogin">注册</el-button>
            <el-button type="primary" plain @click="loginVisible = true" v-if="!isLogin">登录</el-button>
            <el-link @click="handleLoginUserClick(loginUserId)" v-if="isLogin">{{loginUser}}</el-link>
            <el-button type="danger" @click="exit" v-if="isLogin">退出登录</el-button>
        </el-row>
        <hr>

        <!--布局容器-->
        <el-container style="height: 500px; border: 1px solid #eee">
            <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
                <el-menu>
                    <el-menu-item index="1-1">
                        <router-link to="/article">文章</router-link>
                    </el-menu-item>
                    <el-menu-item index="1-2">
                        <router-link to="/boilingPoint">沸点</router-link>
                    </el-menu-item>
                    <el-menu-item index="1-3" v-if="loginUserRole===2">
                        <el-badge :value="isNotReadCount" class="item">
                            <e-link @click="handleNoticeClick(loginUserId)">通知</e-link>
                        </el-badge>
                    </el-menu-item>
                    <el-menu-item index="1-3" v-if="loginUserRole===0||loginUserRole===3">
                        <el-badge :value="isNotAuditedCount" class="item">
                            <e-link @click="handleAdminClick(loginUserId)">管理员界面</e-link>
                        </el-badge>
                    </el-menu-item>
                </el-menu>
            </el-aside>
            <!--文章列表-->
            <el-container>
                <el-header>
                        <el-button size="small" @click="addArticleVisible=true" v-if="loginUserRole===2">发布文章</el-button>
                </el-header>
                <el-main>
                    <el-table :data="tableData">
                        <el-table-column prop="title" label="题目" width="140">
                            <template slot-scope="scope">
                                <el-link @click="read(scope.row)">{{scope.row.title}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="content" label="内容" >
                        </el-table-column>
                        <el-table-column prop="author" label="作者" width="120">
                            <template slot-scope="scope">
                                <el-link @click="getInfo(scope.row)">{{scope.row.author}}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="发布时间" width="120">
                        </el-table-column>
                        <el-table-column prop="viewCount" label="浏览量" width="120">
                        </el-table-column>
                        <el-table-column prop="likeCount" label="点赞量" width="120">
                        </el-table-column>
                        <el-table-column prop="commentCount" label="评论数" width="120">
                        </el-table-column>
                        <el-table-column
                        prop="operate"
                        label="操作"
                        align="center" v-if="loginUserId!==null">
                            <template slot-scope="scope">
                                <el-link @click="deleteArticle(scope.row)" type="danger" v-if="scope.row.authorId===loginUserId||loginUserRole===0||loginUserRole===3">删除</el-link>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!--分页工具条-->
                    <div class="block">
                        <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 20, 50]"
                        :page-size="5"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalCount">
                        </el-pagination>
                    </div>
                </el-main>
            </el-container>
        </el-container>

        <!--登录表单-->
        <el-dialog
                title="登录账号"
                :visible.sync="loginVisible"
                width="30%"
        >
            <el-form :model="user" status-icon :rules="rules" ref="user" label-width="100px" class="demo-user">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="user.username" placeholder="请输入您的账号"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="user.password" autocomplete="off" placeholder="请输入您的密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="login">登录</el-button>
                    <el-button @click="resetForm('user')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--注册表单-->
        <el-dialog
                title="注册账号"
                :visible.sync="registerVisible"
                width="30%"
        >
            <el-form :model="user" status-icon :rules="rules" ref="user" label-width="100px" class="demo-user">
                <el-form-item label="账号" prop="username">
                    <el-input type="text" v-model="user.username" placeholder="请输入5-15位账号" ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="user.password" autocomplete="off" placeholder="请输入5-15位密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input type="password" v-model="user.checkPassword" autocomplete="off" placeholder="请确认密码"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="name">
                    <el-input type="text" v-model="user.name" placeholder="请输入您的昵称"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="user.gender">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="工作" prop="job">
                    <el-input type="text" v-model="user.job" placeholder="请输入您的工作"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input type="text" v-model="user.address" placeholder="请输入您的地址"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="register('user')">注册</el-button>
                    <el-button @click="resetForm('user')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--发布文章表单-->
        <el-dialog
                title="发布文章"
                :visible.sync="addArticleVisible"
                width="30%"
        >
            <el-form label-width="100px" :model="addingArticle" ref="addingArticle">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="addingArticle.title" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input v-model="addingArticle.content" type="textarea"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addArticle">发布</el-button>
                    <el-button @click="resetForm('addingArticle')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    
</template>

<script>

import axios from 'axios';
export default {
    mounted(){
        this.currentPage=1;
        this.getLoginUser();
        this.selectByPage();
    },
    methods:{
        handleSizeChange(val) {
            // 重新设置每页显示的条数
            this.pageSize = val;
            this.selectByPage();
        },
        handleCurrentChange(val) {
            // 重新设置当前页码
            this.currentPage = val;
            this.selectByPage();
        },

        // 分页查询
        selectByPage(){
                axios.get("http://localhost:8080/article?currentPage="+this.currentPage+"&pageSize="+this.pageSize).then((result) =>{
                this.tableData=result.data.data.rows;
                this.totalCount=result.data.data.totalCount;
            })
        },

        // 读取某篇文章
        read(row){
            axios({
                method:"post",
                url:"http://localhost:8080/article/viewCount/"+row.id
            }).then(this.$router.push({ path: '/article/'+row.id}));
        },

        // 登录方法
        login() {
            axios({
                method:"post",
                url:"http://localhost:8080/login",
                data:this.user
            }).then(resp =>{
                // 判断是否存在
                if(resp.data.code){
                    this.resetForm('user');
                    this.loginVisible = false;
                    localStorage.setItem('token',resp.data.data)
                    this.$message.success("登录成功!");
                    this.isLogin=true;
                    this.getLoginUser();
                }else{
                    this.$message.error(resp.data.msg);
                    this.resetForm('user');
                    this.loginVisible = false;
                }
            })
        },

        // 注册用户方法
        register(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios({
                            method:"post",
                            url:"http://localhost:8080/register",
                            data:this.user
                        }).then(resp =>{
                            // 判断是否存在
                            if(resp.data.code){
                                this.$message.success("注册成功！");
                                this.registerVisible=false;                                
                                this.resetForm('user');
                            }else{
                                this.$message.error(resp.data.msg);
                                this.resetForm('user');
                                return false;
                            }
                        })
                    } else {
                        this.$message.error('输入不符合要求！请检查后重新输入');
                        this.resetForm('user');
                        return false;
                    }
                });
            },

        // 检查jwt
        async checkJwt(){
            try {  
                const response = await axios({  
                    method: 'get',  
                    url: 'http://localhost:8080/check/' + localStorage.getItem('token')  
                });  
                return response.data.code;
            } catch (error) {  
                return false; 
            }
        },

        // 获取登录中的用户
        async getLoginUser(){
            if(localStorage.getItem('token')!==null){
                const isValidJwt = await this.checkJwt();
                if(isValidJwt){
                    this.isLogin=true;
                    const parts = localStorage.getItem('token').split('.');
                    if(parts.length>2){
                        const payload = parts[1];
                        const decoded = atob(payload);
                        this.loginUserId=JSON.parse(decoded).id;
                        this.loginUser=JSON.parse(decoded).username;
                        this.loginUserRole=JSON.parse(decoded).role;
                    }
                    if(this.loginUserRole===2){
                        this.getIsNotReadCount();
                    }
                    if(this.loginUserRole===0||this.loginUserRole===3){
                        this.getIsNotAuditedCount();
                    }
                }
            }
        },

        // 获取用户信息方法
        getInfo(row){
            this.$router.push({ path: '/user/'+row.authorId});
        },

        // 处理登录中用户链接被点击
        handleLoginUserClick(row){
            this.$router.push({ path: '/user/'+row});
        },

        // 处理通知链接被点击
        handleNoticeClick(row){
            this.$router.push({ path: '/notice/'+row});
        },
        
        // 处理审核链接被点击
        handleAdminClick(row){
            this.$router.push({ path: '/admin/'+row});
        },

        // 退出登录方法
        exit(){
            localStorage.removeItem('token');
            this.isLogin=false;
            this.loginUser='';
            this.loginUserId='';
            this.loginUserRole=''
        },

        //获取用户未读信息数方法
        getIsNotReadCount(){
            axios({
                method:"get",
                url:"http://localhost:8080/notice/"+this.loginUserId,
                headers:{token:localStorage.getItem("token")}
            }).then(resp => {
                if(resp.data.code){
                    this.isNotReadCount=resp.data.data;
                }else{
                    this.$message.error(resp.data.msg)
                }
            })
        },
        
        //获取管理员未审核数方法
        getIsNotAuditedCount(){
            axios({
                method:"get",
                url:"http://localhost:8080/admin/isNotAudited",
                headers:{token:localStorage.getItem("token")}
            }).then(resp => {
                if(resp.data.code){
                    this.isNotAuditedCount=resp.data.data;
                }else{
                    this.$message.error(resp.data.msg)
                }
            })
        },

        //发布文章
        addArticle(){  
            axios({
                method:"post",
                url:"http://localhost:8080/article",
                data:this.addingArticle,
                headers:{token:localStorage.getItem("token")}
            }).then(resp => {
                if(resp.data.code){
                    this.$message.success("发布文章申请成功，请等待管理员审核！");
                    this.addArticleVisible=false;
                    this.resetForm('addingArticle');
                }else{
                    this.$message.error(resp.data.msg);
                }
            })
        },

        //删除文章
        deleteArticle(row){
            this.$confirm('确定要删除该文章吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios({
                    method:"delete",
                    url:"http://localhost:8080/article/"+row.id,
                    headers:{token:localStorage.getItem("token")}
                }).then(resp => {
                    if(resp.data.code){
                        this.$message.success("删除成功！");
                        this.selectByPage();
                    }else{
                        this.$message.error(resp.data.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        // 重置方法
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
    data() {
        // 检查用户名输入格式
        var checkUsername = (rule, value, callback) => {
                var reg = /^.{5,15}$/;
                if (value === '') {
                    callback(new Error('请输入账号！'));
                } else if(!(reg.test(value))){
                    callback(new Error('长度不符合要求！'));
                } else{
                    callback();
                }
            };
            // 检查第一次密码输入格式
            var validatePass = (rule, value, callback) => {
                var reg = /^.{5,15}$/;
                if (value === '') {
                    callback(new Error('请输入密码！'));
                }else if(!(reg.test(value))){
                    callback(new Error('长度不符合要求！'));
                } else {
                    if (this.user.checkPassword !== '') {
                        this.$refs.user.validateField('checkPassword');
                    }
                    callback();
                }
            };
            // 检查第二次密码是否一致
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码！'));
                } else if (value !== this.user.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
      
        return {
            //文章数据
            tableData: [],
            //总记录数
            totalCount:0,
            //当前页码
            currentPage: 1,
            //每页显示的条数
            pageSize:5,
            //登录对话框是否展示的标记
            loginVisible:false,
            //注册对话框是否展示的标记
            registerVisible:false,
            //是否登录标记
            isLogin:false,
            //发布文章对话框是否展示标记
            addArticleVisible:false,
            //登录中的用户
            loginUser:'',
            //登录中的用户ID
            loginUserId:'',
            //登录中的用户角色
            loginUserRole:'',
            //未读信息数
            isNotReadCount:'',
            //未审核数
            isNotAuditedCount:'',
            //用户模型
            user: {
                username:'',
                password: '',
                checkPassword:'',
                name:'',
                gender:'',
                job:'',
                address:'',
                followCount:'',
                beFollowedCount:''
            },
            //发布中的文章
            addingArticle:{
                title:'',
                content:'',
            },
            rules: {
                username: [
                    { validator: checkUsername, trigger: 'blur' }
                ],
                password: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                checkPassword: [
                    { validator: validatePass2, trigger: 'blur' }
                ]
            }
        }
    }
    
  };

</script>

<style>
.el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }
  
  .el-aside {
    color: #333;
  }
</style>